package org.cglib.example2;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

public class MyMethodInterceptor implements MethodInterceptor {

    Target target;

    public MyMethodInterceptor(Target target) {
        this.target = target;
    }

    public Object getEnhancedInstance() {
        Enhancer e = new Enhancer();
        System.out.println("111");
        e.setSuperclass(target.getClass());
        System.out.println("222");
        e.setCallback(this);
        System.out.println("333");

        /**
         Object key = KEY_FACTORY.newInstance
         KEY_FACTORY信息  {Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$7fb24d72@635}
         key信息    {Enhancer$EnhancerKey$$KeyFactoryByCGLIB$$7fb24d72@703}
         */
        return e.create(); // 这里create()方法,会调用Target类的无参构造
    }

    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
        //obj是代理后的子类,method是调用方法,args是方法入参, proxy是MethodProxy代理对象
        System.out.println("MyMethodInterceptor的intercept方法执行了,方法名是:"+method.getName());

        // 所有可能的6种调用方式
        Object returnVal = proxy.invokeSuper(obj, args);  // 正确, Target类中a方法this is Target$$EnhancerByCGLIB$$e5a0fbe4@28ba21f3
//       Object returnVal  = proxy.invokeSuper(target, args);//报错ClassCastException:  Target cannot be cast to Target$$EnhancerByCGLIB$$e5a0fbe4

//        Object returnVal = proxy.invoke(obj, args);//报错,StackOverflowError,一直调用方法a
//        Object returnVal = proxy.invoke(target, args);//正确,Target类中a方法this is Target@1b4fb997

//        Object returnVal = method.invoke(obj, args);//报错,StackOverflowError,一直调用方法a
//        Object returnVal = method.invoke(target, args);//正确,Target类中a方法this is Target@63c12fb0

        return returnVal;
    }
}